package com.ielts.fragment;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Locale;

import vn.com.baseapplication.BaseApplication;
import vn.com.baseapplication.BaseFragment;
import vn.com.baseapplication.constant.BaseConstant;
import vn.com.baseapplication.service.BaseService;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.ielts.IeltsConstant;
import com.ielts.activity.ChargeMoneyActivity;
import com.ielts.activity.IeltsApplication;
import com.ielts.activity.MainActivity;
import com.ielts.activity.R;
import com.ielts.services.IeltsServices;
import com.ielts.services.IeltsUrl;
import com.nostra13.universalimageloader.core.ImageLoader;

@SuppressLint("SetJavaScriptEnabled")
public class AccountFragment extends BaseFragment implements OnClickListener {
	ImageView avatar;
	TextView name, balance, tvUserId;
	Button chargeMoney, chargeCard;
	WebView wvAccount;
	String userFbLink;
	String userIdStr;
	ImageButton btnClose;

	TextView year;
	ImageView arrow;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mActivity = (MainActivity) getActivity();
		View layout = inflater.inflate(R.layout.fragment_account, null);

		year = (TextView) layout.findViewById(R.id.header_tv_year);
		arrow = (ImageView) layout.findViewById(R.id.header_iv_arrow);
		avatar = (ImageView) layout.findViewById(R.id.imv_avatar);
		name = (TextView) layout.findViewById(R.id.tv_name);
		btnClose = (ImageButton) layout.findViewById(R.id.btn_close);
		wvAccount = (WebView) layout.findViewById(R.id.wv_account);
		balance = (TextView) layout.findViewById(R.id.tv_balance);
		tvUserId = (TextView) layout.findViewById(R.id.tv_userid);
		chargeMoney = (Button) layout.findViewById(R.id.btn_charge_money);
		chargeCard = (Button) layout.findViewById(R.id.btn_charge_card);

		name.setText(IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_NAME, IeltsConstant.KEY_USER_NAME_DEF));
		balance.setText(IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_BALANCE, IeltsConstant.KEY_USER_BALANCE_DEF));

		year.setText("");
		arrow.setVisibility(View.INVISIBLE);

		userFbLink = IeltsApplication.getInstance().getValue(IeltsConstant.KEY_FB_USER_ID, IeltsConstant.KEY_FB_USER_DEF);
		userIdStr = IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
		tvUserId.setText("Code: " + userIdStr + "8");
		try {
			URL img_value = new URL("http://graph.facebook.com/" + userFbLink + "/picture?type=large");
			ImageLoader loader = ImageLoader.getInstance();
			loader.displayImage(img_value.toString(), avatar);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		WebSettings settings = wvAccount.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setDomStorageEnabled(true);

		wvAccount.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				super.onReceivedSslError(view, handler, error);

				// this will ignore the Ssl error and will go forward to your
				// site
				handler.proceed();
			}
		});

		chargeMoney.setOnClickListener(this);
		chargeCard.setOnClickListener(this);
		btnClose.setOnClickListener(this);
		return layout;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (!intent.hasExtra(BaseConstant.MSG_FLAG)) {
			return;
		}
		String FLAG = intent.getStringExtra(BaseConstant.MSG_FLAG);
		if (FLAG != null && FLAG.equals(IeltsConstant.GET_BALANCE + "")) {
			String userBalance = IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_BALANCE, IeltsConstant.KEY_USER_BALANCE_DEF);

			try {
				Locale locale = new Locale("vn", "VN");
				NumberFormat format = NumberFormat.getCurrencyInstance(locale);
				userBalance = format.format(Integer.valueOf(userBalance));
				userBalance = userBalance.substring(1);

				String balanceStr = String.format(getString(R.string.user_banlance), userBalance);
				balance.setText(balanceStr);
			} catch (NumberFormatException e) {
			} catch (IllegalArgumentException e) {
			} catch (IllegalStateException e) {
			}

		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_charge_money:
			// wvAccount.setVisibility(View.VISIBLE);
			// btnClose.setVisibility(View.VISIBLE);

			String urlBank = IeltsUrl.URL_CHARGE_CARD;
			// wvAccount.loadUrl(urlBank + userIdStr);
			showWebViewDialog(urlBank + userIdStr);
			break;
		case R.id.btn_charge_card:
			// wvAccount.setVisibility(View.VISIBLE);
			// btnClose.setVisibility(View.VISIBLE);
			String urlCard = IeltsUrl.URL_CHARGE_MONEY;
			// wvAccount.loadUrl(urlCard + userIdStr);
			showWebViewDialog(urlCard + userIdStr);
			break;
		case R.id.btn_close:
			wvAccount.setVisibility(View.GONE);
			btnClose.setVisibility(View.GONE);
			BaseService services = mActivity.getBaseServices();
			if (services != null)
				((IeltsServices) services).getUserBalance();
			if (Build.VERSION.SDK_INT < 18) {
				wvAccount.clearView();
			} else {
				wvAccount.loadUrl("about:blank");
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		BaseService services = mActivity.getBaseServices();
		if (services != null)
			((IeltsServices) services).getUserBalance();
	}

	public void showWebViewDialog(String url) {
		if (!BaseApplication.haveInternet(mActivity)) {
			BaseApplication.showNoConnectionDialog(mActivity);
			return;
		}

		Intent intent = new Intent(mActivity, ChargeMoneyActivity.class);
		intent.putExtra(BaseConstant.MSG_DATA, url);
		startActivity(intent);
	}
}
